package com.itheima.test;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: Ethan Yankang
 * @Program: JavaUtilsDiy
 * @Date: 2024-08-15 20:26
 **/
public class DiyBuildTreeFromArray {
       public static TreeNode buildTree(Integer[] data) {
               if (data.length == 0 || data[0] == -1) return null;

               Queue<TreeNode> queue = new LinkedList<>();
               TreeNode root = new TreeNode(data[0]);
               queue.add(root);
               int index = 1;

               while (!queue.isEmpty() && index < data.length) {
                   TreeNode currentNode = queue.poll();

                   // Assign left child
                   if (index < data.length && data[index] != -1) {
                       currentNode.left = new TreeNode(data[index]);
                       queue.add(currentNode.left);
                   }
                   index++;

                   // Assign right child
                   if (index < data.length && data[index] != -1) {
                       currentNode.right = new TreeNode(data[index]);
                       queue.add(currentNode.right);
                   }
                   index++;
               }

               return root;
           }
       }


